package com.thinkgsp.jxc.persistence.mybatis;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

/**
 * 查询分页器
 * @author evan
 *
 */
public class QueryPagingHandler {

	private SqlSessionFactory sqlSessionFactory;
	
	private Log log = LogFactory.getLog(QueryPagingHandler.class);
	
	/**
	 * @return the sqlSessionFactory
	 */
	public SqlSessionFactory getSqlSessionFactory() {
		return sqlSessionFactory;
	}

	/**
	 * @param sqlSessionFactory the sqlSessionFactory to set
	 */
	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}

	/**
	 * 查询结果记录数
	 * @param sql
	 * @param params
	 * @return
	 */
	public int queryCount(String sql,Map<String, Object> params) {
		SqlSession sqlSession = null;
		try {
			sqlSession = getSqlSessionFactory().openSession();
			int count = sqlSession.selectOne(sql, params);
			return count;
		} catch(Exception e) {
			log.error(e.getMessage(), e);
		} finally {
			sqlSession.close();
		}
		return 0;
	}
	
	/**
	 * 查询分页的结果集
	 * @param sql
	 * @param params
	 * @param rows
	 * @return
	 */
	public <T> List<T> queryPaging(String sql,Map<String, Object> params,RowBounds rows) {
		SqlSession sqlSession = null;
		try {
			HashMap<String, Object> map = null;
			if(params != null && params.size() > 0) {
				map = new HashMap<String, Object>(params.size() + 2);
				map.putAll(params);
			} else {
				map = new HashMap<String, Object>(2);
			}
			map.put("start", rows.getOffset());
			map.put("size", rows.getLimit());
			sqlSession = getSqlSessionFactory().openSession();
			List<T> list = sqlSession.selectList(sql, map);
			return list;
		} catch(Exception e) {
			log.error(e.getMessage(), e);
		} finally {
			sqlSession.close();
		}
		return new ArrayList<T>(0);
	}
	
	/**
	 * 查询分页结果，返回PagingResult
	 * @param sqlCount
	 * @param sqlQuery
	 * @param params
	 * @param rows
	 * @return
	 */
	public <T> PagingResult<T> queryPagingResult(String sqlCount,String sqlQuery,
			Map<String,Object> params,RowBounds rows) {
		PagingResult<T> result = new PagingResult<T>();
		int count = queryCount(sqlCount, params);
		result.setTotalCount(count);
		if(count > 0) {
			List<T> list = queryPaging(sqlQuery, params, rows);
			result.setList(list);
		} else {
			List<T> list = new ArrayList<T>(0);
			result.setList(list);
		}
		return result;
	}
}
